package statisticalhandler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"sync"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/placeincome"
	"yundian/internel/app/models/statistics"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/export"
)

// 经营概况统计(其它类型)
func ManageSummaryStatisticalTypeList(c *gin.Context) {
	param := &struct {
		IsAdmin uint8 `json:"isAdmin" form:"isAdmin"`
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	isAdmin, _ := helper.GetIsAdminFromCtx(c)

	data := dao.NewStatisticalDao().ManageSummaryStatisticalTypeDao(isAdmin, param.IsAdmin)
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, []map[string]interface{}{})(ServerError)
	}

	Response(c)("", CodeSuccess, ResponseList{
		Data: data.Unwrap(),
	})(OK)
}

// 经营概况统计
func ManageSummaryStatisticalList(c *gin.Context) {
	isAdmin, _ := helper.GetIsAdminFromCtx(c)

	data := dao.NewStatisticalDao().ManageSummaryStatisticalDao(isAdmin)
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, []map[string]interface{}{})(ServerError)
	}

	Response(c)("", CodeSuccess, ResponseList{
		Data: data.Unwrap(),
	})(OK)
}

//代理统计报表
func AgentStatisticalList(c *gin.Context) {
	param := &struct {
		UserName    string `json:"userName" form:"userName" `
		SelectTime  string `json:"selectTime" form:"selectTime"`
		BaseListReq request.BaseListReq
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//获取数据
	data := dao.NewStatisticalDao().AgentStatisticalListDao(param.UserName, param.SelectTime, &param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data.Data)(ServerError)
	}

	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

//网点统计报表
func PlaceStatisticalList(c *gin.Context) {
	param := &struct {
		PlaceName   string `json:"placeName" form:"placeName"`
		SelectTime  string `json:"selectTime" form:"selectTime"`
		BaseListReq request.BaseListReq
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//获取数据
	data := dao.NewStatisticalDao().PlaceStatisticalListDao(param.PlaceName, param.SelectTime, &param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data)(ServerError)
	}
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

//设备统计报表
func DeviceStatisticalList(c *gin.Context) {
	param := &struct {
		DeviceTypeName string `json:"deviceTypeName" form:"deviceTypeName"`
		SelectTime     string `json:"selectTime" form:"selectTime"`
		BaseListReq    request.BaseListReq
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//获取数据
	data := dao.NewStatisticalDao().DeviceStatisticalListDao(param.DeviceTypeName, param.SelectTime, &param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data)(ServerError)
	}
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

//网点对账单
func PlaceAccountCheckingList(c *gin.Context) {
	param := &request.PlaceListReq{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()
	data := dao.NewStatisticalDao().PlaceAccountCheckingListDao(param)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data)(ServerError)

	}
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)

}

//项目营业统计
func ProjectStatisticalList(c *gin.Context) {
	param := &struct {
		UserName    string `json:"userName" form:"userName"`
		BaseListReq request.BaseListReq
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	data := dao.NewStatisticalDao().ProjectStatisticalListDao(param.UserName, &param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data.Data)(ServerError)
	}
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)

}

//月运营统计
func MonthStatisticalList(c *gin.Context) {
	param := &struct {
		UserName    string `json:"userName" form:"userName"`
		SelectMonth string `json:"statisticalMonth" form:"selectMonth"`
		BaseListReq request.BaseListReq
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()
	data := dao.NewStatisticalDao().MonthStatisticalListDao(param.UserName, param.SelectMonth, &param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data)(ServerError)
	}
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

//项目代理管理
func ProjectUserManagementList(c *gin.Context) {
	param := &struct {
		UserName    string `json:"userName" form:"userName"`
		BaseListReq request.BaseListReq
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()
	data := dao.NewStatisticalDao().ProjectUserManagementListDao(param.UserName, &param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data)(ServerError)
	}
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

//项目网点管理
func ProjectPlaceManagementList(c *gin.Context) {
	param := &struct {
		PlaceName   string `json:"placeName" form:"placeName"`
		BaseListReq request.BaseListReq
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()
	data := dao.NewStatisticalDao().ProjectPlaceManagementListDao(param.PlaceName, &param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data)(ServerError)
	}
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

//项目订单管理
func ProjectOrderManagementList(c *gin.Context) {
	param := &struct {
		Name        string `json:"name" form:"name"`
		EndTime     string `json:"endTime" form:"endTime"`
		BaseListReq request.BaseListReq
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	data := dao.NewStatisticalDao().ProjectOrderManagementListDao(param.Name, param.EndTime, &param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data)(ServerError)
	}

	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

func SearchUserTypeList(c *gin.Context) {
	param := &struct {
		Name        string `json:"name" form:"name"`
		BaseListReq request.BaseListReq
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()
	data := dao.NewStatisticalDao().SearchUserTypeListDao(param.Name, &param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data)(ServerError)
	}

	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

func SearchPlaceTypeList(c *gin.Context) {
	param := &struct {
		PlaceName   string `json:"placeName" form:"placeName"`
		UserName    string `json:"userName" form:"userName"`
		BaseListReq request.BaseListReq
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()
	data := dao.NewStatisticalDao().SearchPlaceTypeListDao(param.PlaceName, param.UserName, &param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data)(ServerError)
	}

	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

func SearchDeviceTypeList(c *gin.Context) {
	param := &struct {
		DeviceType  string `json:"deviceType" form:"deviceType"`
		BaseListReq request.BaseListReq
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()
	data := dao.NewStatisticalDao().SearchDeviceTypeListDao(param.DeviceType, &param.BaseListReq)
	//错误处理
	if data.Err != nil {
		Response(c)("", CodeInternalServerError, data)(ServerError)
	}

	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

func GetRegionsParentList(c *gin.Context) {
	param := &struct {
		ParentId int `json:"parentId" form:"parentId"`
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	Response(c)("", CodeSuccess, dao.NewPlaceDao().GetRegionsListByParent(param.ParentId).Unwrap())(OK)

}

func GetRegionsList(c *gin.Context) {
	param := &struct {
		Level int `json:"level" form:"level"`
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	Response(c)("", CodeSuccess, dao.NewStatisticalDao().GetRegionsList(param.Level).Unwrap())(OK)

}

// ------------统计重构
func AgentIncomeList(c *gin.Context) {
	param := &request.AgentStatisticsReportReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	loginUserId, err := helper.GetUserIdFromCtx(c) // 获取当前代理商ID
	isAdmin, _ := helper.GetIsAdminFromCtx(c)
	parentId, err := helper.GetParentIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()

	param.LoginUserId = loginUserId
	param.IsAdmin = isAdmin

	// 超级管理员 && 运营商下的员工
	if isAdmin == helper.TypeNumIsAdminAdministrator || (isAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		param.LoginUserId = 2
		param.IsAdmin = helper.TypeNumIsAdminOperator
		if param.UserId == 0 {
			param.UserId = 2
		}
	}

	if param.UserId == 0 {
		param.UserId = loginUserId
	}

	data := dao.NewStatisticalDao().AgentIncomeDayStatisticsListDao(param)
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
	return
}

func AgentIncomeAllList(c *gin.Context) {
	param := &request.AgentStatisticsReportReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	loginUserId, err := helper.GetUserIdFromCtx(c) // 获取当前代理商ID
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isAdmin, _ := helper.GetIsAdminFromCtx(c)
	param.LoginUserId = loginUserId
	param.IsAdmin = isAdmin

	if param.UserId == 0 {
		param.UserId = loginUserId
	}

	//data := dao.NewStatisticalDao().AgentIncomeDayStatisticsAllListDao(param)
	//Response(c)("", CodeSuccess, ResponseList{
	//	PageNo:     param.BaseListReq.PageNo,
	//	PageSize:   param.BaseListReq.PageSize,
	//	TotalCount: data.Val().(int64),
	//	TotalPage:  0,
	//	Data:       data.Unwrap(),
	//})(OK)
	//return
}

func BranchIncomeList(c *gin.Context) {
	param := &request.AgentStatisticsReportReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	loginUserId, err := helper.GetUserIdFromCtx(c) // 获取当前代理商ID
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isAdmin, _ := helper.GetIsAdminFromCtx(c)
	param.LoginUserId = loginUserId
	param.IsAdmin = isAdmin

	if param.UserId == 0 {
		param.UserId = loginUserId
	}

	data := dao.NewStatisticalDao().BranchIncomeDayStatisticsListDao(param)
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}

//func BranchIncomeList(c *gin.Context) {
//	param := &struct {
//		UserName    string `json:"userName" form:"userName" `
//		SelectTime  string `json:"selectTime" form:"selectTime"`
//		MonthType   int    `json:"type" form:"type"`
//		SharedMode  string `json:"sharedMode" form:"sharedMode"`
//		BaseListReq request.BaseListReq
//	}{}
//	dingo.ErrorIf(c.Bind(param)).Unwrap()
//	loginUserId, err := helper.GetUserIdFromCtx(c) // 获取当前代理商ID
//	if err != nil {
//		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
//		return
//	}
//	isAdmin, err := helper.GetIsAdminFromCtx(c) // 从上下文中获取用户是否为管理员
//	if err != nil {
//		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
//		return
//	}
//	isPlace, err := helper.GetIsPlaceFromCtx(c)
//	if err != nil {
//		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
//		return
//	}
//
//	data := dao.NewStatisticalDao().BranchIncomeListDao(param.UserName, param.SelectTime, param.MonthType, param.SharedMode, &param.BaseListReq, loginUserId, isAdmin, isPlace)
//	Response(c)("", CodeSuccess, ResponseList{
//		PageNo:     param.BaseListReq.PageNo,
//		PageSize:   param.BaseListReq.PageSize,
//		TotalCount: data.Val().(int64),
//		TotalPage:  0,
//		Data:       data.Unwrap(),
//	})(OK)
//}

func OrdersStatisticsList(c *gin.Context) {
	param := &struct {
		PlaceName   string `json:"placeName" form:"placeName" `
		SelectTime  string `json:"selectTime" form:"selectTime"`
		MonthType   int    `json:"type" form:"type"`
		SharedMode  string `json:"sharedMode" form:"sharedMode"`
		BaseListReq request.BaseListReq
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()

	loginUserId, err := helper.GetUserIdFromCtx(c) // 获取当前代理商ID
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isAdmin, err := helper.GetIsAdminFromCtx(c) // 从上下文中获取用户是否为管理员
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	//loginUserId := 27
	//var isAdmin uint8
	//isAdmin = 3

	data := dao.NewStatisticalDao().OrdersStatisticsListDao(loginUserId, isAdmin, param.PlaceName, param.SelectTime, param.MonthType, param.SharedMode, &param.BaseListReq)
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)

}

func PlaceStatisticsList(c *gin.Context) {

	loginUserId, err := helper.GetUserIdFromCtx(c) // 获取当前代理商ID
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isAdmin, err := helper.GetIsAdminFromCtx(c) // 从上下文中获取用户是否为管理员
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	IsDraw, err := helper.GetIsDrawFromCtx(c) // 从上下文中获取
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	parentId, _ := helper.GetParentIdFromCtx(c)

	param := &struct {
		PlaceName   string `json:"placeName" form:"placeName" `
		SelectTime  string `json:"selectTime" form:"selectTime"`
		MonthType   int    `json:"type" form:"type"`
		SharedMode  string `json:"sharedMode" form:"sharedMode"`
		BaseListReq request.BaseListReq
	}{}

	dingo.ErrorIf(c.Bind(param)).Unwrap()

	// 超级管理员 && 运营商下的员工
	if isAdmin == helper.TypeNumIsAdminAdministrator || (isAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		loginUserId = 2
		isAdmin = helper.TypeNumIsAdminAdministrator
	}

	//loginUserId := 2
	//var isAdmin uint8
	//isAdmin = 2
	switch param.MonthType {
	case 3:
		data := dao.NewStatisticalDao().
			PlaceStatisticsAllListDao(loginUserId, isAdmin, IsDraw, param.PlaceName, &param.BaseListReq)
		lists := data.Unwrap().([]*placeincome.PlaceIncomeAllModel)

		Response(c)("", CodeSuccess, ResponseList{
			PageNo:     param.BaseListReq.PageNo,
			PageSize:   param.BaseListReq.PageSize,
			TotalCount: data.Val().(int64),
			TotalPage:  0,
			Data:       lists,
		})(OK)
		return
	case 2:
		data := dao.NewStatisticalDao().
			PlaceRealTimeMonthStatisticsList(loginUserId, isAdmin, param.PlaceName, param.SelectTime, param.MonthType, param.SharedMode, &param.BaseListReq)
		lists := data.Unwrap().([]*placeincome.PlaceIncomeModel)

		Response(c)("", CodeSuccess, ResponseList{
			PageNo:     param.BaseListReq.PageNo,
			PageSize:   param.BaseListReq.PageSize,
			TotalCount: data.Val().(int64),
			TotalPage:  0,
			Data:       lists,
		})(OK)
		return
	case 1:
		data := dao.NewStatisticalDao().
			PlaceRealTimeDayStatisticsList(loginUserId, isAdmin, param.PlaceName, param.SelectTime,
				param.MonthType, param.SharedMode, &param.BaseListReq)
		lists := data.Unwrap().([]*placeincome.PlaceIncomeModel)

		//for _, lst := range lists {
		//	lst.ScanCount = lst.OrderCount
		//	lst.DeviceCount = lst.DeviceTotal
		//	//// 激活设备量
		//	//lst.DeviceCount = dao.NewDeviceDao().GetDeviceCountByPlaceId(lst.PlaceId).Unwrap().(int64)
		//	//// 扫码量
		//	//lst.ScanCount = dao.NewOrderDao().GetPlaceOrderScanCountByPlaceId(lst.PlaceId, int64(lst.CreateAt)).Unwrap().(int64)
		//	// 有产设备量
		//	lst.ActiveDevCount = dao.NewOrderDao().GetActiveDevCount(lst.PlaceId, lst.IncomeDay).Unwrap().(int64)
		//}

		Response(c)("", CodeSuccess, ResponseList{
			PageNo:     param.BaseListReq.PageNo,
			PageSize:   param.BaseListReq.PageSize,
			TotalCount: data.Val().(int64),
			TotalPage:  0,
			Data:       lists,
		})(OK)
		return

	}
	//if param.MonthType == 3 {
	//	data := dao.NewStatisticalDao().
	//		PlaceStatisticsAllListDao(loginUserId, isAdmin, IsDraw, param.PlaceName, &param.BaseListReq)
	//	lists := data.Unwrap().([]*placeincome.PlaceIncomeAllModel)
	//
	//	Response(c)("", CodeSuccess, ResponseList{
	//		PageNo:     param.BaseListReq.PageNo,
	//		PageSize:   param.BaseListReq.PageSize,
	//		TotalCount: data.Val().(int64),
	//		TotalPage:  0,
	//		Data:       lists,
	//	})(OK)
	//	return
	//} else {
	//	data := dao.NewStatisticalDao().
	//		PlaceStatisticsListDao(loginUserId, isAdmin, param.PlaceName, param.SelectTime,
	//			param.MonthType, param.SharedMode, &param.BaseListReq)
	//	lists := data.Unwrap().([]*placeincome.PlaceIncomeModel)
	//
	//	for _, lst := range lists {
	//		lst.ScanCount = lst.OrderCount
	//		lst.DeviceCount = lst.DeviceTotal
	//		//// 激活设备量
	//		//lst.DeviceCount = dao.NewDeviceDao().GetDeviceCountByPlaceId(lst.PlaceId).Unwrap().(int64)
	//		//// 扫码量
	//		//lst.ScanCount = dao.NewOrderDao().GetPlaceOrderScanCountByPlaceId(lst.PlaceId, int64(lst.CreateAt)).Unwrap().(int64)
	//		// 有产设备量
	//		lst.ActiveDevCount = dao.NewOrderDao().GetActiveDevCount(lst.PlaceId, lst.IncomeDay).Unwrap().(int64)
	//	}
	//
	//	Response(c)("", CodeSuccess, ResponseList{
	//		PageNo:     param.BaseListReq.PageNo,
	//		PageSize:   param.BaseListReq.PageSize,
	//		TotalCount: data.Val().(int64),
	//		TotalPage:  0,
	//		Data:       lists,
	//	})(OK)
	//	return
	//}

}

func DividendsList(c *gin.Context) {
	param := &struct {
		PlaceId     int    `json:"placeName" form:"placeId" `
		SelectTime  string `json:"selectTime" form:"selectTime"`
		UserId      int    `json:"userName" form:"userId" `
		TradeNo     string `json:"tradeNo" form:"tradeNo"`
		SharedMode  string `json:"sharedMode" form:"sharedMode"`
		BaseListReq request.BaseListReq
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	loginUserId, err := helper.GetUserIdFromCtx(c) // 获取当前代理商ID
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isAdmin, err := helper.GetIsAdminFromCtx(c) // 从上下文中获取用户是否为管理员
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	parentId, _ := helper.GetParentIdFromCtx(c)

	// 超级管理员 && 运营商下的员工
	if isAdmin == helper.TypeNumIsAdminAdministrator || (isAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		loginUserId = 2
	}

	data := dao.NewStatisticalDao().DividendsListDao(param.PlaceId, param.SelectTime, param.UserId, param.TradeNo, param.SharedMode, &param.BaseListReq, loginUserId, isAdmin)
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)

}

// 手动统计
func ManualReport(c *gin.Context) {
	param := &struct {
		StatisticsType int        `json:"statisticsType" form:"statisticsType" `
		StatisticsTime dingo.Time `json:"statisticsTime" form:"statisticsTime"`
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	formatTime := time.Unix(int64(param.StatisticsTime), 0).Format("2006-01-02")

	fmt.Println("haha: ", formatTime, param.StatisticsTime, param.StatisticsType)

	switch param.StatisticsType {
	case 1:
		// 代理 日收入统计
		logic.NewTaskLogic().SeparateAgentIncomeStatistics(formatTime, "pcl")
	case 2:
		// 分公司 日收入统计

	case 3:
		// 商户 日收入统计
		logic.NewTaskLogic().SeparatePlaceIncomeStatistics(formatTime, "pcl")
	}

	Response(c)("手动统计已执行，请稍后查看数据", CodeSuccess, ResponseList{})(OK)

}

//项目统计
func ProjectStatisticsList(c *gin.Context) {
	param := &request.ProjectStatisticsReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	loginUserId, err := helper.GetUserIdFromCtx(c) // 获取当前代理商ID
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isAdmin, _ := helper.GetIsAdminFromCtx(c)
	param.LoginUserId = loginUserId
	param.LoginIsAdmin = isAdmin

	//if param.UserId == 0 {
	//	param.UserId = loginUserId
	//}

	//param.LoginUserId = 2
	//param.LoginIsAdmin = 2

	data := dao.NewStatisticalDao().ProjectDayStatisticsList(param)
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
	return
}

func InternalStatisticsList(c *gin.Context) {
	param := &request.InternalStatisticsReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	loginUserId, err := helper.GetUserIdFromCtx(c) // 获取当前代理商ID
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isAdmin, _ := helper.GetIsAdminFromCtx(c)
	param.LoginUserId = loginUserId
	param.LoginIsAdmin = isAdmin

	//param.LoginUserId = 2
	//param.LoginIsAdmin = 2

	data := dao.NewStatisticalDao().GetInternalStatisticsList(param)
	Response(c)("", CodeSuccess, ResponseList{
		PageNo:     param.BaseListReq.PageNo,
		PageSize:   param.BaseListReq.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
	return

}

// ----------------------- 新统计 handler ------------------ //

// 基础数据分析
func HandleGetAnalysis(ctx *gin.Context) {
	param := &struct {
		DateStr  string `json:"dateStr" form:"dateStr"`
		DateType string `json:"dateType" form:"dateType"` // 时间类型
	}{}
	dingo.ErrorIf(ctx.Bind(param)).Unwrap()
	var data *statistics.BasicAnalysis
	var dateStr string
	if param.DateStr == "" || param.DateStr == time.Now().Format("2006-01-02") {
		dateStr = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	} else {
		dateStr = param.DateStr
	}
	switch param.DateType {
	case "day":
		data = dao.NewStatisticsDao().GetStatisticsDataByDay(dateStr).Unwrap().(*statistics.BasicAnalysis)
		break
	default:
		data = dao.NewStatisticsDao().GetStatisticsDataByDay(dateStr).Unwrap().(*statistics.BasicAnalysis)
	}
	data.UpdateTime = global.Rdb.Get(ctx, "statistics_update_time").Val() // 更新时间
	data.NowDate = time.Now().Format("2006-01-02") + " " + helper.GetWeek(time.Now().Weekday().String())

	var wg sync.WaitGroup
	wg.Add(4)
	go func() {
		defer wg.Done()
		data.SettlementChart = dao.NewStatisticsDao().GetSettlementChart().Unwrap().([]statistics.SettlementChart) // 获取流水折线图
		data.IncomeChart = dao.NewStatisticsDao().GetIncomeChart().Unwrap().([]statistics.IncomeChart)             // 获取收益折线图
		data.UvChart = dao.NewStatisticsDao().GetUvChart().Unwrap().([]statistics.UvChart)                         // 获取收益折线图
	}()
	go func() {
		defer wg.Done()
		data.AdIncomeChart = dao.NewStatisticsDao().GetAdIncomeChart().Unwrap().([]statistics.AdIncomeChart) // 广告柱状图
		data.CashChart = dao.NewStatisticsDao().GetCashChart().Unwrap().([]statistics.CashChart)             // 提现柱状图
	}()
	go func() {
		defer wg.Done()
		data.PriceChart = dao.NewStatisticsDao().GetPriceChart().Unwrap().([]statistics.PriceChart)               // 订单笔数
		data.SaleChart = dao.NewStatisticsDao().GetSaleChartByDay().Unwrap().([]statistics.SaleChart)             // 获取动销图表
		data.SaleRateChart = dao.NewStatisticsDao().GetSaleRateChartByDay().Unwrap().([]statistics.SaleRateChart) // 获取动销率图表
	}()
	go func() {
		defer wg.Done()
		data.ScanChart = dao.NewStatisticsDao().GetScanChartByDate().Unwrap().([]statistics.ScanChart)             // 扫码图表
		data.ConvRateChart = dao.NewStatisticsDao().GetConvRateChartByDate().Unwrap().([]statistics.ConvRateChart) // 转化率
	}()
	wg.Wait()

	Response(ctx)("", CodeSuccess, data)(OK)
}

func HandleGetAnalysisNormal(ctx *gin.Context) {
	param := &struct {
		DateStr  string `json:"dateStr" form:"dateStr"`
		DateType string `json:"dateType" form:"dateType"` // 时间类型
	}{}
	dingo.ErrorIf(ctx.Bind(param)).Unwrap()
	var data *statistics.BasicAnalysisNormal
	var dateStr string
	if param.DateStr == "" || param.DateStr == time.Now().Format("2006-01-02") {
		dateStr = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	} else {
		dateStr = param.DateStr
	}
	switch param.DateType {
	case "day":
		data = dao.NewStatisticsDao().GetStatisticsNormalDataByDay(dateStr).Unwrap().(*statistics.BasicAnalysisNormal)
		break
	default:
		data = dao.NewStatisticsDao().GetStatisticsNormalDataByDay(dateStr).Unwrap().(*statistics.BasicAnalysisNormal)
	}
	data.UpdateTime = global.Rdb.Get(ctx, "statistics_update_time").Val() // 更新时间
	data.NowDate = time.Now().Format("2006-01-02") + " " + helper.GetWeek(time.Now().Weekday().String())

	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		defer wg.Done()
		data.SettlementChart = dao.NewStatisticsDao().GetSettlementNormalChart().Unwrap().([]statistics.SettlementNormalChart) // 获取流水折线图
	}()
	go func() {
		defer wg.Done()
		data.PriceChart = dao.NewStatisticsDao().GetPriceChartNormal().Unwrap().([]statistics.PriceChart)               // 订单笔数
		data.SaleChart = dao.NewStatisticsDao().GetSaleChartByDay().Unwrap().([]statistics.SaleChart)             // 获取动销图表
	}()
	wg.Wait()

	Response(ctx)("", CodeSuccess, data)(OK)
}

// 获取数据列表
func HandleGetAnalysisList(ctx *gin.Context) {
	param := &request.AnalysisListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewStatisticsDao().GetAnalysisList(param)
	lists := data.Unwrap().([]*statistics.StatisticsModel)

	// 分页信息
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       lists,
	})(OK)
}

// 手动统计校验基础数据分析
func HandleOrderBasicStatistics(c *gin.Context) {
	param := &struct {
		DateStr string `json:"dateStr" form:"dateStr"`
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	var dateList []string
	dateList = append(dateList, param.DateStr)

	logic.NewTaskStatisticsLogic().StatisticsByDateStr(dateList)
	Response(c)("", CodeSuccess, "统计成功")(OK)
	return
}

// UV数据新增修改
func HandleUpdateUvData(ctx *gin.Context) {
	param := &request.UvDataInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	data := dao.NewStatisticsDao().UpdateUvData(param).Unwrap()

	Response(ctx)("", CodeInsertSuccess, data)(OK)
}

// 基础分析数据导出
func HandelBasicAnalysisExport(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	// 请求参数处理
	param := &request.AnalysisListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	// 查询结果
	data := dao.NewStatisticsDao().GetAnalysisList(param)
	lists := data.Unwrap().([]*statistics.StatisticsModel)

	var newFileName = "statistics-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	_, errByWriteExcel := export.BasicAnalysisDataExport(lists, "数据分析列表", global.Cfg.Export.ExportPath+"template_statistics.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		Response(ctx)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
		return
	}
	dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, userId, ctx.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "经营分析数据导出")
	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
}

// 用户分析数据列表
func HandleGetAnalysisListByUser(ctx *gin.Context) {
	param := &request.AnalysisUserListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewStatisticsDao().GetAnalysisUserList(param)
	lists := data.Unwrap().([]*statistics.StatisticsUserList)

	// 分页信息
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       lists,
	})(OK)
}

func HandleGetTeamRankList(ctx *gin.Context) {
	param := &request.AnalysisUserListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	dateStr := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	data := dao.NewStatisticsDao().GetUserTeamRankList(param, dateStr)
	lists := data.Unwrap().([]*statistics.StatisticsUserTeamRankList)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       lists,
	})(OK)
}

func HandleGetPlaceRankList(ctx *gin.Context) {
	param := &request.AnalysisUserListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	dateStr := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	data := dao.NewStatisticsDao().GetUserPlaceRankList(param, dateStr)
	lists := data.Unwrap().([]*statistics.StatisticsUserPlaceRankList)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       lists,
	})(OK)
}

// 代理商用户流水排行
func HandleGetSettlementRankList(ctx *gin.Context) {
	param := &request.AnalysisUserListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewStatisticsDao().GetUserSettlementRankList(param)
	lists := data.Unwrap().([]*statistics.StatisticsUserSettlementRankList)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       lists,
	})(OK)
}

func HandleGetIncomeRankList(ctx *gin.Context) {
	param := &request.AnalysisUserListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewStatisticsDao().GetUserIncomeRankList(param)
	lists := data.Unwrap().([]*statistics.StatisticsUserIncomeRankList)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       lists,
	})(OK)
}

// 按日手动统计用户
func HandleOrderStatisticsByUser(ctx *gin.Context) {
	param := &struct {
		DateType string `json:"dateType" form:"dateType" `
		DateStr  string `json:"dateStr" form:"dateStr"`
		UserId   int    `json:"userId" form:"userId"`
	}{}
	dingo.ErrorIf(ctx.Bind(param)).Unwrap()

	if param.UserId > 0 {
		if ok := logic.NewTaskStatisticsUserLogic().StatisticsByTypeByUserId(param.DateStr, param.UserId); ok {
			Response(ctx)("", CodeSuccess, "统计成功")(OK)
			return
		} else {
			Response(ctx)("", CodeSuccess, "统计失败")(OK)
			return
		}
	} else {
		var dateList []string
		dateList = append(dateList, param.DateStr)
		if ok := logic.NewTaskStatisticsUserLogic().StatisticsByTypeByHaveOrders(dateList); ok {
			Response(ctx)("", CodeSuccess, "统计成功")(OK)
			return
		} else {
			Response(ctx)("", CodeSuccess, "统计失败")(OK)
			return
		}
	}

}

func HandelAnalysisUserExport(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &request.AnalysisUserListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewStatisticsDao().GetAnalysisUserList(param)
	lists := data.Unwrap().([]*statistics.StatisticsUserList)

	var newFileName = "statistics-user-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	_, errByWriteExcel := export.AnalysisUserDataExport(lists, "数据分析列表", global.Cfg.Export.ExportPath+"template_statistics_user.xlsx", global.Cfg.Export.ExportExcel+newFileName)
	if errByWriteExcel != nil {
		Response(ctx)(errByWriteExcel.Error(), CodeSuccess, newFileName)(OK)
		return
	}
	dingo.Task(logic.NewLogsLogic().InsertDownloadLog, func() {}, userId, ctx.ClientIP(), newFileName, global.Cfg.Export.ExportExcel+newFileName, "代理分析数据导出")
	Response(ctx)("", CodeSuccess, newFileName)(OK)
	return
}

// 获取扫码量，扫码UV量
func HandleGetScanLogs(ctx *gin.Context) {
	param := &struct {
		DateStr  string `json:"dateStr" form:"dateStr"`
		DateType string `json:"dateType" form:"dateType"` // 时间类型
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewStatisticsDao().GetScanChartByDay().Unwrap().([]*statistics.ScanChart)

	// 分页信息
	Response(ctx)("", CodeSuccess, data)(OK)
}
